package com.frxuexi.park2303.user

import androidx.lifecycle.MutableLiveData
import com.frxuexi.base.entity.UserBean
import com.frxuexi.base.http.ApiService
import com.frxuexi.base.mvi.BaseViewModel
import com.frxuexi.base.mvi.RequestType
import com.google.gson.Gson
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject

@HiltViewModel
class UserViewModel @Inject constructor(val apiService: ApiService) : BaseViewModel<UserIntent>() {
    val userData = MutableLiveData<UserBean>()
    val userError = MutableLiveData<String>()

    val registerData = MutableLiveData<UserBean>()
    val registerError = MutableLiveData<String>()
    override fun handleIntent(it: UserIntent) {
        when (it) {
            is UserIntent.register -> httpRequestLive(
                apiService.register(it.uname, it.pwd),
                {
                    if (it != null) {
                        val userBean =
                            Gson().fromJson<UserBean>(Gson().toJson(it), UserBean::class.java)
                        registerData.postValue(userBean)
                    }
                },
                registerError::postValue
            )

            is UserIntent.login -> httpRequestLive(apiService.login(it.uname, it.pwd), {
                val userBean =
                    Gson().fromJson<UserBean>(Gson().toJson(it), UserBean::class.java)
                userData.postValue(userBean)
            },userError::postValue)
            is UserIntent.getParkByType->httpRequest(apiService.getParkByType("标准车位"))
            is UserIntent.getVisitByName->httpRequest(apiService.getVisitsByName(it.uname),RequestType.VISIT)
            is UserIntent.getRepairByName->httpRequest(apiService.getRepairByName(it.uname),RequestType.REPAIR)
            is UserIntent.getPatrolByUid->httpRequest(apiService.getPatrolByUid(it.uid),RequestType.PATROL)

            is UserIntent.updatePark->httpRequest(apiService.updatePark(it.id,toBody(it.item)),RequestType.UPDATE)
            is UserIntent.getVisits->httpRequest(apiService.getVisits(),RequestType.VISIT)
            is UserIntent.approveVisit->httpRequest(apiService.approveVisit(it.id),RequestType.UPDATE)
            is UserIntent.rejectVisit->httpRequest(apiService.rejectVisit(it.id),RequestType.UPDATE)
            is UserIntent.getNews->httpRequest(apiService.getNews(),RequestType.NEWS)
        }
    }
}